package com.homestay.controller;


import com.homestay.beans.Home;
import com.homestay.exception.HomeException;
import com.homestay.service.HomeService;
import com.homestay.service.impl.HomeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@WebServlet("/home")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 5,
        maxFileSize = 1024 * 1024 * 10,
        maxRequestSize = 1024 * 1024 * 50
)
public class HomeServlet extends HttpServlet {

    HomeService homeService = new HomeServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置请求编码,防止乱码
        req.setCharacterEncoding("utf-8");
        // 设置响应内容类型,防止乱码
        resp.setContentType("text/html;charset=utf-8");

        String action = req.getParameter("action");
        switch (action) {
            case "query":
                homeQuery(req, resp);
                break;
            case "add":
                homeAdd(req, resp);
                break;
            case "delete":
                homeDelete(req, resp);
                break;
            case "goupdate":
                goUpdate(req, resp);
                break;
            case "update":
                homeUpdate(req, resp);
                break;
            case "show":
                homeShow(req, resp);
                break;
            default:
                break;
        }
    }

    private void homeUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("img");
        // 获取上传目录的绝对路径
        String path = req.getServletContext().getRealPath("upload");
        // 获取所有上传的文件
        Collection<Part> parts = req.getParts();
        // 处理每个文件
        for (Part part : parts) {
            // 获取原始的文件名
            String fileName = getFileName(part);
            if (fileName != null && !fileName.isEmpty()) {
                //随机生成文件名
                name = UUID.randomUUID() + "." + fileName.split("\\.")[1];
                // 保存文件
                String filePath = req.getServletContext().getRealPath("upload") + "/" + name;
                name = "/upload/" + name;
                part.write(filePath);
                //System.out.println("文件上传成功，文件上传的路径:"+filePath);
            }
        }

        // 获取请求参数
        String id = req.getParameter("id");
        String num = req.getParameter("num");
        String h_type = req.getParameter("h_type");
        String price = req.getParameter("price");
        String state = req.getParameter("state");
        String img = name;
        String text = req.getParameter("text");
        Home home = new Home(Integer.parseInt(id), Integer.parseInt(num), h_type, price, state, img, text);
        // 调用服务层方法添加
        int count = homeService.update(home);
        if (count > 0) {
            resp.getWriter().write("<script>alert('修改成功');location.href='/home?action=query'</script>");
        } else {
            resp.getWriter().write("<script>alert('修改失败');location.href='/views/home_update.jsp'</script>");
        }

    }

    // 跳转修改页面
    private void goUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Home home = homeService.queryById(id);
        req.setAttribute("home", home);
        req.getRequestDispatcher("/views/home_update.jsp").forward(req, resp);
    }

    //显示房间详情
    private void homeShow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Home home = homeService.queryById(id);
        req.setAttribute("home", home);
        req.getRequestDispatcher("/views/home_show.jsp").forward(req, resp);
    }

    //删除房间
    private void homeDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        try {
            int count = homeService.deleteById(id);
            if (count > 0) {
                resp.getWriter().write("<script>alert('删除成功');location.href='/home?action=query'</script>");
            } else {
                resp.getWriter().write("<script>alert('删除失败');location.href='/home?action=query'</script>");
            }
        } catch (HomeException e) {
            resp.getWriter().write("<script>alert('"+ e.getMessage() +"');location.href='/home?action=query'</script>");
        }
    }

    // 查询房间列表
    private void homeQuery(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String h_type = req.getParameter("h_type");
        String state = req.getParameter("state");
        String num = req.getParameter("num");
        if (h_type == null || h_type.isEmpty()) {
            h_type = "";
        }
        if (state == null || state.isEmpty()) {
            state = "";
        }
        if (num == null || num.isEmpty()) {
            num = "";
        }
        // 调用服务层方法查询
        List<Home> homes = homeService.query(h_type, state, num);
        // 将查询结果存储到请求属性中
        req.setAttribute("homeList", homes);
        req.setAttribute("num", num);
        req.setAttribute("h_type", h_type);
        req.setAttribute("state", state);
        // 转发到结果页面
        req.getRequestDispatcher("/views/home_list.jsp").forward(req, resp);
    }

    // 添加房间
    private void homeAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        String name = "";
        // 获取上传目录的绝对路径
        String path = req.getServletContext().getRealPath("upload");
        // 获取所有上传的文件
        Collection<Part> parts = req.getParts();
        // 处理每个文件
        for (Part part : parts) {
            // 获取原始的文件名
            String fileName = getFileName(part);
            if (fileName != null && !fileName.isEmpty()) {
                //随机生成文件名
                name = UUID.randomUUID().toString() + "." + fileName.split("\\.")[1];
                // 保存文件
                String filePath = req.getServletContext().getRealPath("upload") + "\\" + name;
                part.write(filePath);
                //System.out.println("文件上传成功，文件上传的路径:"+filePath);
            }
        }

        // 获取请求参数
        String num = req.getParameter("num");
        String h_type = req.getParameter("h_type");
        String price = req.getParameter("price");
        String state = req.getParameter("state");
        String img = "/upload/" + name;
        String text = req.getParameter("text");
        Home home = new Home(Integer.parseInt(num), h_type, price, state, img, text);
        try {
            // 调用服务层方法添加
            int count = homeService.add(home);
            if (count > 0) {
                resp.getWriter().write("<script>alert('添加成功');location.href='/home?action=query'</script>");
            } else {
                resp.getWriter().write("<script>alert('添加失败');location.href='/views/home_add.jsp'</script>");
            }
        } catch (HomeException e) {
            String message = e.getMessage();
            // 获取错误信息
            req.setAttribute("error", message);
            req.setAttribute("home", home);
            req.getRequestDispatcher("/views/home_add.jsp").forward(req, resp);
        }
    }

    // 从Part对象中获取文件名
    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        String[] elements = contentDisposition.split(";");
        for (String element : elements) {
            if (element.trim().startsWith("filename")) {
                // 提取文件名
                String fileName = element.substring(element.indexOf('=') + 1).trim().replace("\"", "");
                // 如果文件名包含路径分隔符，只保留文件名部分
                int index = fileName.lastIndexOf(File.separator);
                return (index > 0) ? fileName.substring(index + 1) : fileName;
            }
        }
        return null;
    }
}
